package com.pactera.bledemo.activity.ble

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.dylanc.viewbinding.nonreflection.binding
import com.pactera.bledemo.R
import com.pactera.bledemo.activity.thirdparty.BleThirdPartyDetailActivity
import com.pactera.bledemo.adapter.BleAdapter
import com.pactera.bledemo.bean.BleBean
import com.pactera.library.bluetooth.BleManager
import com.pactera.bledemo.databinding.ActivityBleactivityBinding
import com.pactera.library.bluetooth.event.BleManagerEvent
import com.pactera.library.listener.ConnectManagerCallback
import com.pactera.library.utils.ToastUtil
import java.util.*

class BLEActivity : AppCompatActivity() {
    private val TAG = "BLEActivity"
    private val binding by binding(ActivityBleactivityBinding::inflate)

    lateinit var ble: BleManager

    lateinit var mAdapter: BleAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.apply {
            actionToolbar.tvTitle.text = "BLE低功耗蓝牙(推荐)"
            actionToolbar.imgBack.setOnClickListener { finish() }
        }
        ble = BleManager.getInstance(this)

        binding.apply {
            mAdapter = BleAdapter();
            mRecyclerView.layoutManager = LinearLayoutManager(this@BLEActivity)
            mRecyclerView.adapter = mAdapter
            mAdapter.addChildClickViewIds(R.id.btnPair, R.id.tvConnect)
        }
        registerBleReceiver()

        if (!ble.isEnableBLE()) {
            //若没打开则打开蓝牙
            ble.enableBLE(this)
        } else {
            ble.startDiscoveryBLE();
        }


        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            val address = item.address
            val device = item.device

            goalAddressDevice = address

            when (view.id) {
                R.id.btnPair -> {
                    val result = ble.createBond(device)
                    println("ClientActivity.onCreate result=$result")
                    if (result) {
                        ToastUtil.showToast("发起配对成功")
                    } else {
                        ToastUtil.showToast("发起配对失败")
                    }
                }
                R.id.tvConnect -> {
                    ble.cancelDiscoveryBLE()

                    val intent = Intent(this@BLEActivity, BLEDetailActivity::class.java)
                    intent.putExtra("name", device?.name);
                    intent.putExtra("address", device?.address);
                    startActivity(intent)

                }
                else -> {
                }
            }
        }

    }

    private fun registerBleReceiver() {
        val filter = IntentFilter()
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        filter.addAction(BluetoothDevice.ACTION_FOUND)

        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
        registerReceiver(receiver, filter)
    }

    private var goalAddressDevice: String? = null

    /**
     * 定义广播接收器
     */
    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.i(TAG, "onReceive: action=$action")
            if (action == BluetoothAdapter.ACTION_DISCOVERY_STARTED) {
                Log.i(TAG, "onReceive:  扫描开始")
            } else if (action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED) {
                Log.i(TAG, "onReceive:  扫描完成")
            } else if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
                Log.i(TAG, "onReceive: 状态改变广播")
            } else if (action == BluetoothDevice.ACTION_FOUND) {
                Log.i(TAG, "onReceive:  发现周围设备广播")
                val bluetoothDevice: BluetoothDevice? =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                val name = bluetoothDevice?.name
                val address = bluetoothDevice?.address

                Log.i(TAG, "onReceive:  name=$name address=$address")
                val mBean = BleBean();
                mBean.device = bluetoothDevice;
                mBean.name = name;
                mBean.address = address;
                mAdapter.addData(mBean)
            } else if (action == BluetoothDevice.ACTION_PAIRING_REQUEST) {
                Log.i(TAG, "onReceive: 配对请求广播")
                val btDevice =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                Log.i(TAG, "onReceive: btDevice.getAddress()=" + btDevice!!.address)
                /*if (btDevice.address == goalAddressDevice) {
                    val pin = "1234" //默认不是1234 就是 0000
                    try {
                        ClsUtils.setPairingConfirmation(btDevice.javaClass, btDevice, true) //1确认配对
                        abortBroadcast() //2.终止有序广播; 如果没有将广播终止，则会出现一个一闪而过的配对框。
                        val ret: Boolean =
                            ClsUtils.setPin(btDevice.javaClass, btDevice, pin) //3.调用setPin方法进行配对...
                        Log.i(TAG, "onReceive: ret=$ret")
                        if (ret) {
                            Toast.makeText(context, "配对成功", Toast.LENGTH_SHORT).show();
                            //把设备地址和名字保存到本地
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }*/


            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "onActivityResult: 请求码=$requestCode 结果码=$resultCode")
        when (resultCode) {
            RESULT_OK -> {
                Log.i(TAG, "onActivityResult: 蓝牙已打开")
                ble.startDiscoveryBLE()
            }
            RESULT_CANCELED -> {
                Log.i(TAG, "onActivityResult: 打开请求被拒绝")
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ble.cancelDiscoveryBLE()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }
}


//测试发现这种方式，扫描的不对 小米8（android10）oppo也是
/* mBleManager.scanLeDevice(true, object : ScanCallback() {
     override fun onBatchScanResults(results: MutableList<ScanResult>?) {
         super.onBatchScanResults(results)
         Log.i(TAG, "scanLeDevice: size=${results?.size}")
     }

     override fun onScanFailed(errorCode: Int) {
         super.onScanFailed(errorCode)
         Log.i(TAG, "scanLeDevice: errorCode=$errorCode")
     }

     override fun onScanResult(callbackType: Int, result: ScanResult?) {
         super.onScanResult(callbackType, result)
         Log.i(TAG, "scanLeDevice: callbackType=$callbackType")
         val device = result?.device
         val name = device?.name
         val address = device?.address
         Log.i(TAG, "scanLeDevice:  name=$name address=$address")

         val mBean = BleBean();
         mBean.name = name;
         mBean.address = address;
         mAdapter.addData(mBean)
     }
 })*/
/*  //测试发现这种方式，扫描的不对 小米8（android10）oppo也是
mBleManager.scanLeDevice(true, object : BluetoothAdapter.LeScanCallback {
    override fun onLeScan(device: BluetoothDevice?, rssi: Int, scanRecord: ByteArray?) {
        val name = device?.name
        val address = device?.address
        Log.i(TAG, "scanLeDevice:  name=$name address=$address")
        val mBean = BleBean();
        mBean.name = name;
        mBean.address = address;
        mAdapter.addData(mBean)
    }

})*/